/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2024 All Rights Reserved.
 */
package com.alipay.demo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.alipay.demo.service.AntMerchantShopService;
import com.alipay.demo.service.ImageUploadService;
import com.alipay.demo.service.LocalItemService;
import com.alipay.demo.util.AlipayApiCallback;
import com.alipay.demo.util.AlipayApiTemplate;
import com.alipay.demo.util.AlipaySdkUtil;
import com.alipay.demo.vo.LocalItemCreateRequest;
import com.alipay.demo.vo.OpenResponse;
import com.alipay.demo.vo.UserShopVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author jishupei.jsp
 * @version : LocalItemServiceImpl, v0.1 2024年03月04日 2:55 下午 jishupei.jsp Exp $
 */
@Service
public class LocalItemServiceImpl implements LocalItemService {

    private static final Logger logger = LogManager.getLogger(LocalItemServiceImpl.class);

    @Autowired
    private AlipaySdkUtil alipaySdkUtil;

    @Autowired
    private AntMerchantShopService antMerchantShopService;

    @Autowired
    private ImageUploadService imageUploadService;

    @Override
    public OpenResponse<List<LocalAppxCategoryVO>> getCategories(String itemType) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<List<LocalAppxCategoryVO>, AlipayOpenAppLocalitemAllcategoryQueryResponse>() {
            @Override
            public AlipayOpenAppLocalitemAllcategoryQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemAllcategoryQueryRequest request = new AlipayOpenAppLocalitemAllcategoryQueryRequest();
                AlipayOpenAppLocalitemAllcategoryQueryModel model = new AlipayOpenAppLocalitemAllcategoryQueryModel();

                // 设置商品类型
                model.setItemType(itemType);

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public List<LocalAppxCategoryVO> getData(AlipayOpenAppLocalitemAllcategoryQueryResponse response) {
                List<LocalCategoryAndParentVO> cats = response.getCats();
                if (CollectionUtils.isEmpty(cats)) {
                    return null;
                }
                List<LocalAppxCategoryVO> childs = new ArrayList<>();
                for (LocalCategoryAndParentVO cat : cats) {
                    if (CollectionUtils.isEmpty(cat.getCatAndParent())) {
                        continue;
                    }
                    // 获取状态为资质已开通的叶子节点
                    Optional<LocalAppxCategoryVO> categoryVO = cat.getCatAndParent().stream().filter(Objects::nonNull)
                            .filter(child -> "AUDIT_PASSED".equalsIgnoreCase(child.getCatStatus())).findFirst();
                    categoryVO.ifPresent(childs::add);
                }
                return childs;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.allcategory.query";
            }
        });
    }

    @Override
    public OpenResponse<AlipayOpenAppLocalitemTemplateQueryResponse> queryTemplate(String categoryId, String itemType) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AlipayOpenAppLocalitemTemplateQueryResponse, AlipayOpenAppLocalitemTemplateQueryResponse>() {
            @Override
            public AlipayOpenAppLocalitemTemplateQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemTemplateQueryRequest request = new AlipayOpenAppLocalitemTemplateQueryRequest();
                AlipayOpenAppLocalitemTemplateQueryModel model = new AlipayOpenAppLocalitemTemplateQueryModel();

                // 设置类目id
                model.setCategoryId(categoryId);

                // 设置商品类型
                model.setItemType(itemType);

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public AlipayOpenAppLocalitemTemplateQueryResponse getData(AlipayOpenAppLocalitemTemplateQueryResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.template.query";
            }
        });
    }

    @Override
    public OpenResponse<String> createLocalItem(String itemType, LocalItemCreateRequest param) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AlipayOpenAppLocalitemCreateResponse>() {
            @Override
            public AlipayOpenAppLocalitemCreateResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemCreateRequest request = new AlipayOpenAppLocalitemCreateRequest();
                AlipayOpenAppLocalitemCreateModel model = getAlipayOpenAppLocalitemCreateModel(param);

                // 设置商品模版类型
                model.setItemType(itemType);

                // 设置属性列表
                model.setAttrs(getItemAttrs(param, model.getItemType()));
                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AlipayOpenAppLocalitemCreateResponse response) {
                return response.getItemId();
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.create";
            }
        });
    }

    @Override
    public OpenResponse<String> createCalendarLocalItem(LocalItemCreateRequest param) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AlipayOpenAppLocalitemCreateResponse>() {
            @Override
            public AlipayOpenAppLocalitemCreateResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemCreateRequest request = new AlipayOpenAppLocalitemCreateRequest();
                AlipayOpenAppLocalitemCreateModel model = getAlipayOpenAppLocalitemCreateModel(param);

                // 设置商品模版类型
                model.setItemType("7");

                // 设置标品ID
                model.setSpuId(param.getSpuId());

                // 设置属性列表
                model.setAttrs(getItemAttrs(param, model.getItemType()));
                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AlipayOpenAppLocalitemCreateResponse response) {
                return response.getItemId();
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.create";
            }
        });
    }

    @Override
    public OpenResponse<String> updateLocalItem(String itemType, LocalItemCreateRequest param) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AlipayOpenAppLocalitemModifyResponse>() {
            @Override
            public AlipayOpenAppLocalitemModifyResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemModifyRequest request = new AlipayOpenAppLocalitemModifyRequest();
                AlipayOpenAppLocalitemModifyModel model = new AlipayOpenAppLocalitemModifyModel();
                AlipayOpenAppLocalitemCreateModel createModel = getAlipayOpenAppLocalitemCreateModel(param);

                // 设置商品模版类型
                model.setItemType(itemType);

                // 设置类目ID
                model.setCategoryId(param.getCategoryId());

                // 设置商家侧商品ID
                model.setOutItemId(param.getOutItemId());

                // 设置C端详情页模式
                model.setItemDetailsPageModel(createModel.getItemDetailsPageModel());

                model.setSoldTime(createModel.getSoldTime());

                // 设置商家名称
                model.setMerchantName(createModel.getMerchantName());

                // 设置商品名称
                model.setTitle(param.getProductName());

                model.setCustomerServiceMobile(createModel.getCustomerServiceMobile());

                // 设置属性列表
                model.setAttrs(getItemAttrs(param, model.getItemType()));

                // 设置sku列表
                LocalItemSkuModifyVO skus0 = new LocalItemSkuModifyVO();
                skus0.setOriginalPrice(100L);
                skus0.setSalePrice(1L);
                skus0.setSaleStatus("AVAILABLE");
                skus0.setStockNum("9999");
                model.setSkus(skus0);

                // 设置商品主图
                model.setHeadImg(createModel.getHeadImg());

                // 设置商品图片的文件id列表
                model.setImageList(createModel.getImageList());

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AlipayOpenAppLocalitemModifyResponse response) {
                return response.getItemId();
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.modify";
            }
        });
    }

    @Override
    public OpenResponse<Boolean> deleteLocalItem(String itemId, String outItemId) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<Boolean, AlipayOpenAppItemDeleteResponse>() {

            @Override
            public AlipayOpenAppItemDeleteResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemDeleteRequest request = new AlipayOpenAppItemDeleteRequest();
                AlipayOpenAppItemDeleteModel model = new AlipayOpenAppItemDeleteModel();

                if (!StringUtils.isEmpty(outItemId)) {
                    // 设置商家侧商品ID列表
                    List<String> outItemIdList = new ArrayList<>();
                    outItemIdList.add(outItemId);
                    model.setOutItemIdList(outItemIdList);
                }
                if (!StringUtils.isEmpty(itemId)) {
                    // 设置支付宝平台侧商品ID
                    List<String> itemIdList = new ArrayList<>();
                    itemIdList.add(itemId);
                    model.setItemIdList(itemIdList);
                }

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public Boolean getData(AlipayOpenAppItemDeleteResponse response) {
                return response.isSuccess() && !CollectionUtils.isEmpty(response.getRecords());
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.delete";
            }
        });

    }

    @Override
    public OpenResponse<AlipayOpenAppLocalitemQueryResponse> queryItemDetail(String itemId, String outItemId, String needEditSpu) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AlipayOpenAppLocalitemQueryResponse, AlipayOpenAppLocalitemQueryResponse>() {
            @Override
            public AlipayOpenAppLocalitemQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemQueryRequest request = new AlipayOpenAppLocalitemQueryRequest();
                AlipayOpenAppLocalitemQueryModel model = new AlipayOpenAppLocalitemQueryModel();

                if (!StringUtils.isEmpty(itemId)) {
                    // 设置支付宝侧商品id
                    model.setItemId(itemId);
                }

                if (!StringUtils.isEmpty(outItemId)) {
                    // 设置商家侧商品id
                    model.setOutItemId(outItemId);
                }

                // 设置是否查询编辑版本（默认查编辑版本）
                model.setNeedEditSpu(StringUtils.isEmpty(needEditSpu) ? "1" : needEditSpu);

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public AlipayOpenAppLocalitemQueryResponse getData(AlipayOpenAppLocalitemQueryResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.query";
            }
        });
    }

    @Override
    public OpenResponse<AlipayOpenAppLocalitemListQueryResponse> queryItemList(Long pageNum, Long pageSize, List<String> itemIdList, List<String> outItemIdList, String spuStatus) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AlipayOpenAppLocalitemListQueryResponse, AlipayOpenAppLocalitemListQueryResponse>() {
            @Override
            public AlipayOpenAppLocalitemListQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppLocalitemListQueryRequest request = new AlipayOpenAppLocalitemListQueryRequest();
                AlipayOpenAppLocalitemListQueryModel model = new AlipayOpenAppLocalitemListQueryModel();

                // 设置页码
                model.setPageNum(pageNum == null ? 1L : pageNum);

                // 设置单页大小
                model.setPageSize(pageSize == null ? 10L : pageSize);

                // 设置商家侧id列表
                model.setOutItemIdList(outItemIdList);

                // 设置平台侧商品id列表
                model.setItemIdList(itemIdList);

                if (!StringUtils.isEmpty(spuStatus)) {
                    // 设置商品SPU状态
                    model.setSpuStatus(spuStatus);
                }

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public AlipayOpenAppLocalitemListQueryResponse getData(AlipayOpenAppLocalitemListQueryResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.localitem.list.query";
            }
        });
    }

    private AlipayOpenAppLocalitemCreateModel getAlipayOpenAppLocalitemCreateModel(LocalItemCreateRequest param) throws AlipayApiException {
        AlipayOpenAppLocalitemCreateModel model = new AlipayOpenAppLocalitemCreateModel();

        // 设置类目ID
        model.setCategoryId(param.getCategoryId());

        // 设置商家侧商品ID
        model.setOutItemId(param.getOutItemId());

        // 设置C端详情页模式
        model.setItemDetailsPageModel("1");

        // 设置售卖时间
        TimeRangeStructVO soldTime = new TimeRangeStructVO();
        soldTime.setEndTime(param.getEndTime());
        soldTime.setStartTime(param.getStartTime());
        model.setSoldTime(soldTime);

        // 设置商家名称
        model.setMerchantName(param.getMerchantName());

        // 设置商品名称
        model.setTitle(param.getProductName());

        // 设置客服电话
        PhoneStructVO customerServiceMobile = new PhoneStructVO();
        customerServiceMobile.setPhoneNumber("18888888888");
        customerServiceMobile.setPhoneType("1");
        model.setCustomerServiceMobile(customerServiceMobile);

        // 设置sku列表
        List<LocalItemSkuCreateVO> skus = new ArrayList<>();
        LocalItemSkuCreateVO skus0 = new LocalItemSkuCreateVO();
        skus0.setOriginalPrice(100L);
        skus0.setSalePrice(1L);
        skus0.setSaleStatus("AVAILABLE");
        skus0.setStockNum(9999L);
        skus.add(skus0);
        model.setSkus(skus);

        // 设置商品主图
        model.setHeadImg(imageUploadService.uploadAndReturnId("file/head2.jpg", "ITEM_HEAD_IMG"));

        // 设置商品图片的文件id列表
        List<String> imageList = new ArrayList<>();
        imageList.add(imageUploadService.uploadAndReturnId("file/head2.jpg", "ITEM_IMAGE_LIST"));
        model.setImageList(imageList);

        return model;
    }

    private List<AppItemAttrVO> getItemAttrs(LocalItemCreateRequest param, String itemType) {
        List<AppItemAttrVO> attrs = new ArrayList<>();
        List<AttributeVO> attributes = queryTemplateAttrList(param.getCategoryId(), itemType);
        if (CollectionUtils.isEmpty(attributes)) {
            return attrs;
        }
        for (AttributeVO attr : attributes) {
            if ("use_shop".equals(attr.getKey())) {
                // 特殊处理
                attr.setIsRequired(true);
            }
            if (!attr.getIsRequired()) {
                continue;
            }
            AppItemAttrVO appItemAttrVO = new AppItemAttrVO();
            appItemAttrVO.setAttrKey(attr.getKey());
            switch (attr.getKey()) {
                // -----BEGIN 共同属性 -----
                case "use_shop":
                    List<UserShopVo> userShopVos;
                    if (CollectionUtils.isEmpty(param.getShopIds())) {
                        // 不存在则取所有正常状态的门店
                        userShopVos = antMerchantShopService.queryNormalShopInfos().stream()
                                .map(info -> new UserShopVo(info.getShopId())).collect(Collectors.toList());
                    } else {
                        userShopVos = param.getShopIds().stream()
                                .map(UserShopVo::new).collect(Collectors.toList());
                    }
                    appItemAttrVO.setAttrValue(JSONArray.toJSONString(userShopVos));
                    break;
                case "settle_type":
                    // "1"代表统一收款类型
                    appItemAttrVO.setAttrValue("{\"settle_type\":\"1\",\"settle_pid_info\":\"" + alipaySdkUtil.getPid() + "\"}");
                    break;
                case "preorder_rule":
                    appItemAttrVO.setAttrValue("{\"need_appointment\":true,\"appointment_instruction\":\"预约说明：请至少提前一天预约。\"}");
                    break;
                case "contact_info_type":
                    // "1"代表需要顾客手机号
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "sold_time":
                    appItemAttrVO.setAttrValue("{\"start_time\": \"" + param.getStartTime() + "\",\"end_time\": \"" + param.getEndTime() + "\"}");
                    break;
                case "item_details_page_model":
                    // 1:官方插件版
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "coupon_usage_rule":
                    // "1"：不可使用商家优惠券
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "refund_rule":
                    if ("7".equals(itemType)) {
                        // 退款规则，免费退:1;不可退:4;阶梯退:5
                        appItemAttrVO.setAttrValue("{\"refund_policy\": [\"1\"]}");
                    } else {
                        // "1"代表随时可退，"2"代表过期未核销自动退
                        appItemAttrVO.setAttrValue("{\"refund_policy\": [\"1\", \"2\"]}");
                    }
                    break;
                // -----END 共同属性 -----

                // -----BEGIN 本地团购券/代金券/次卡商品可传入以下属性 -----
                case "original_price_source":
                    // "1"：需设置单品原价，commodity.price 必须指定值。商品
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "commodity":
                    appItemAttrVO.setAttrValue("[{\"group_name\":\"主食\",\"total_count\":2,\"option_count\":1,\"item_list\":[{\"name\":\"经典蛋炒饭\",\"count\":1,\"price\":2155,\"unit\":\"元\"},{\"name\":\"火腿蛋炒饭\",\"count\":1,\"price\":2355,\"unit\":\"元\"}]},{\"group_name\":\"饮料\",\"total_count\":1,\"option_count\":1,\"item_list\":[{\"name\":\"可乐\",\"count\":1,\"price\":450,\"unit\":\"元\"}]}]");
                    break;
                case "limit_stock_rule":
                    // 库存200个
                    appItemAttrVO.setAttrValue("{\"limit\":\"1\",\"num\":\"200\"}");
                    break;
                case "limit_buy_rule":
                    // 没人限购10个
                    appItemAttrVO.setAttrValue("{\"limit\":\"1\",\"num\":\"10\"}");
                    break;
                case "usage_type":
                    // "1"代表到店亮码
                    appItemAttrVO.setAttrValue("{\"usage_list\":[{\"use_type\":\"1\"}]}");
                    break;
                case "code_source_type":
                    // "1"代表三方码核销（商家码核销）, "2"代表一方码核销（支付宝码核销）
                    appItemAttrVO.setAttrValue(StringUtils.isEmpty(param.getCodeSourceType()) ? "1" : param.getCodeSourceType());
                    break;
                case "verify_type":
                    // 券码生成方式为三方码时核销方式仅为商家自有方式核销
                    // "1"代表商家用支付宝 POS 小程序验证核销，"2"代表商家用自有方式核销。
                    appItemAttrVO.setAttrValue("[\"2\"]");
                    break;
                case "use_date":
                    // "2" 代表指定天数，生效后180天后失效
                    appItemAttrVO.setAttrValue("{\"use_date_type\":\"2\",\"day_duration\":\"180\"}");
                    break;
                case "use_limit":
                    appItemAttrVO.setAttrValue("{\"use_time_type\":\"2\",\"use_date_list\":[{\"days_of_week\":[\"1\",\"2\",\"3\",\"4\",\"5\"],\"start_time\":\"09:00:00\",\"end_time\":\"21:30:00\",\"end_time_type\":\"SAME_DAY\"}],\"can_no_use_date_list\":[{\"holidays\":[{\"start_time\":\"09:00:00\",\"end_time\":\"21:30:00\",\"end_time_type\":\"SAME_DAY\"}]}]}");
                    break;
                case "merchant_refund_confirm":
                    // "1"代表退款需商家确认（需接入spi.alipay.marketing.certificate.order.refundconfirm），"2"代表退款无需商家确认。
                    appItemAttrVO.setAttrValue("1");
                    break;
                // -----END 本地团购券/代金券/次卡商品可传入以上属性 -----

                // -----BEGIN 本地次卡商品可传入以下属性 -----
                case "consumption_times":
                    // "1"代表退款需商家确认（需接入spi.alipay.marketing.certificate.order.refundconfirm），"2"代表退款无需商家确认。
                    appItemAttrVO.setAttrValue("3");
                    break;
                // -----END 本地次卡商品可传入以上属性 -----

                // -----BEGIN 酒店日历房商品可传入以下属性 -----
                case "rp_type":
                    // 售卖类型，1-全日房
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "breakfast_num":
                    // 早餐份数，0-无早
                    appItemAttrVO.setAttrValue("0");
                    break;
                case "payment_type":
                    // 支付类型，预付:1;现付:2
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "customer_service_mobile":
                    // 客服电话
                    appItemAttrVO.setAttrValue("{\"phone_type\":\"1\",\"phone_number\":\"13222122121\"}");
                    break;
                // -----END 酒店日历房商品可传入以上属性 -----
            }
            attrs.add(appItemAttrVO);
        }
        return attrs;
    }

    /**
     * 获取本地商品模板信息
     */
    public List<AttributeVO> queryTemplateAttrList(String categoryId, String itemType) {
        OpenResponse<AlipayOpenAppLocalitemTemplateQueryResponse> templateResponse = queryTemplate(categoryId, itemType);
        if ("10000".equals(templateResponse.getCode())) {
            return templateResponse.getData().getAttr().getItemAttrList();
        }
        logger.error("查询本地商品模板失败");
        return null;
    }

}
